use bevy::asset::{AssetEvent, AssetServer, Assets, Handle};
use bevy::image::{Image, ImageAddressMode, ImageSampler, ImageSamplerDescriptor};
use bevy::math::Vec3;
use bevy::pbr::{MeshMaterial3d, StandardMaterial};
use bevy::prelude::{default, Camera3d, Commands, Component, EventReader, Mesh, Mesh3d, Query, Rectangle, Res, ResMut, Resource, Transform, Window};
use bevy::render::mesh::VertexAttributeValues;
use bevy::render::render_resource::Extent3d;


#[derive(Component)]
pub(crate) struct PhotoFrame;

pub fn init_scene(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    asset_server: Res<AssetServer>,
    window: Query<&Window>,
    mut assets_images: ResMut<Assets<Image>>,
) {
    //获取窗口长宽比例,调整画框大小
    let window_first = window.iter().next().unwrap();
    let width = window_first.width();
    let height = window_first.height();

    //修复应状态栏发生的畸变
    println!("width height {}:{}!",width, height);

    let f_window = width/height;

    let handle: bevy::prelude::Handle<Image> = asset_server.load_override("default_image.png");
    // let handle: Handle<Image> = asset_server.load_override("C:\\Users\\lyh\\Desktop\\18.png");

    // 设置纹理采样器
    if let Some(image) = assets_images.get_mut(&handle) {
        image.sampler = ImageSampler::Descriptor(ImageSamplerDescriptor {
            address_mode_u: ImageAddressMode::ClampToEdge,
            address_mode_v: ImageAddressMode::ClampToEdge,
            ..default()
        });
    }

    let rectangle = Rectangle::from_size((6. * 1.777 / f_window, 6.).into());


    let handle1:Handle<Mesh> = meshes.add(rectangle);

    let material = materials.add(StandardMaterial {
        unlit: true, // 关键设置 - 不受光照影响
        base_color_texture: Some(handle.clone_weak()),
        ..default()
    });

    commands.spawn((
        Mesh3d(handle1.clone_weak()),
        MeshMaterial3d(material.clone()),
        Transform::default(),
        PhotoFrame
    ));

    commands.insert_resource(InLineAssets{
        photo_frame:handle,
        mash3d:handle1,
        material,
    });

    // 3D camera
    commands.spawn((
        Camera3d::default(),
        Transform::from_xyz(0., 0., 7.5).looking_at(Vec3::ZERO, Vec3::Y),
    ));
}



#[derive(Resource)]
pub(crate) struct InLineAssets {
    //当前相片帧,用于标记当前在相框的图片
    pub photo_frame: Handle<Image>,
    //相框形状句柄
    pub mash3d: Handle<Mesh>,
    //相框纹理
    pub material: Handle<StandardMaterial>,
}


pub(crate) fn listen_for_specific_assets(
    game_assets: Res<InLineAssets>,
    mut events: EventReader<AssetEvent<Image>>,
    mut meshes: ResMut<Assets<Mesh>>,
    assets_images: Res<Assets<Image>>,
) {
    for event in events.read() {
        if let AssetEvent::Added { id } = event {
            if id == &game_assets.photo_frame.id() {
                println!("Player texture loaded!");
                // let handle = game_assets.mash3d.clone_weak();
                if let Some(mesh) = meshes.get_mut(&game_assets.mash3d) {
                    // 获取顶点位置属性
                    if let Some(VertexAttributeValues::Float32x3(positions)) =
                        mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION)
                    {

                        let extent3d = if let Some(image) = assets_images.get(&game_assets.photo_frame) {
                            image.texture_descriptor.size
                        }else {
                            Extent3d::default()
                        };

                        let image_height = extent3d.height as f32;
                        let image_width = extent3d.width  as f32;

                        let f_image =  image_width/image_height;

                        // 更新顶点位置
                        positions[0][0] = positions[0][0]*f_image; // 左下
                        positions[1][0] = positions[1][0]*f_image;  // 右下
                        positions[2][0] = positions[2][0]*f_image;   // 右上
                        positions[3][0] = positions[3][0]*f_image;  // 左上

                    }

                    // 更新网格的AABB边界
                    // mesh.compute_aabb();
                }
            }
        }
    }
}
